<template>
	<view class="container">
		<view class="tui-line-cell-img">
			<view class="tui-upload-box">
				<view class="tui-upload-item" v-if="actFile != ''">
					<image :src="actFile" class="tui-upload-img" @tap="toCoverSelect" mode="aspectFill"></image>
				</view>
				<view class="tui-upload-item" v-if="actFile == ''" hover-class="tui-opcity" :hover-stay-time="150" @tap="toCoverSelect">
					<text class="tui-upload-item-text">上传封面</text>
				</view>
			</view>
		</view>
		<form @submit="formSubmit" @reset="formReset">
			<!-- 			<tui-list-cell :hover="false">
				<view class="tui-line-cell-img">
					<view class="tui-upload-box">
						<view class="tui-upload-item" v-if="actFile != ''"><image :src="actFile" class="tui-upload-img" @tap="chooseImage" mode="aspectFit"></image></view>
						<view class="tui-upload-item" v-if="actFile == ''" hover-class="tui-opcity" :hover-stay-time="150" @tap="chooseImage">
							<text class="tui-upload-item-text">上传封面（4:3 比例图片）</text>
						</view>
					</view>
				</view>
			</tui-list-cell> -->
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">分类</view>
					<view class="uni-list-cell-db">
						<picker @change="bindPickerChange" :value="selectActTypeIndex" :range="actTypeList" range-key="title">
							<view class="uni-input">{{ actTypeList[selectActTypeIndex].title }}</view>
						</picker>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">主题</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="actItem.actTitle" name="actTitle" placeholder="请输入聚会主题" maxlength="50" type="text" />
				</view>
			</tui-list-cell>

			<!-- 时间控件 -->
			<tui-list-cell @tap="showStartTime()" hover-class="opcity" :hover-stay-time="150">
				<view class="tui-line-cell">
					<view class="tui-title">开始时间</view>
					<view class="tui-title-value">
						<text>{{ startTime }}</text>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell @tap="showEndTime()" hover-class="opcity" :hover-stay-time="150">
				<view class="tui-line-cell">
					<view class="tui-title">结束时间</view>
					<view class="tui-title-value">
						<text>{{ endTime }}</text>
					</view>
				</view>
			</tui-list-cell>

			<tui-list-cell @tap="chooseLocation()" hover-class="opcity" :hover-stay-time="150">
				<view class="tui-line-cell">
					<view class="tui-title">聚会地点</view>
					<view class="tui-title-value">
						<text>{{ locationAddress }}</text>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">人数限制</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="actItem.peopleMax" name="peopleMax" placeholder="参与人数限制(0表示不限制)" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">费用预计(元)</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="actItem.price"  name="price" placeholder="AA费用(0表示免费)" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell-img-group">
					<view class="tui-title">群二维码</view>
					<view class="tui-upload-box">
						<view class="tui-upload-item-group" v-if="actGroupFile != ''">
							<image :src="actGroupFile" class="tui-upload-img" @tap="chooseImageGroup" mode="aspectFit"></image>
						</view>
						<view class="tui-upload-item-group" v-if="actGroupFile == ''" hover-class="tui-opcity" :hover-stay-time="150" @tap="chooseImageGroup">
							<text class="tui-upload-item-text">上传</text>
						</view>
					</view>
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">联系手机(选填)</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="actItem.linkmanPhone" name="linkmanPhone" placeholder="请输入手机号" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">联系微信(选填)</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="actItem.linkmanWx" name="linkmanWx" placeholder="请输入微信号" maxlength="50" type="text" />
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false">
				<view class="tui-line-cell">
					<view class="tui-title">组织酬劳(元)</view>
					<input placeholder-class="phcolor" class="tui-input" v-model="actItem.reward" name="reward" placeholder="打赏组织者(0表示免费公益)" maxlength="50" type="text" />
				</view>
			</tui-list-cell>

			<view class="tui-btn-box">
				<button class="btn-primary" hover-class="btn-hover" formType="submit" type="primary">下一步</button>
				<!-- <button class="btn-primary btn-gray" hover-class="btn-gray-hover" formType="reset">重置</button> -->
			</view>
		</form>
		<tui-datetime
			ref="startTime"
			:type="1"
			:startYear="startYear"
			:endYear="endYear"
			:cancelColor="cancelColor"
			:color="color"
			:setDateTime="setDateTime"
			@confirm="changeTimeStart"
		></tui-datetime>
		<tui-datetime
			ref="endTime"
			:type="1"
			:startYear="startYear"
			:endYear="endYear"
			:cancelColor="cancelColor"
			:color="color"
			:setDateTime="setDateTime"
			@confirm="changeTimeEnd"
		></tui-datetime>
	</view>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
const form = require('../../components/utils/formValidation.js');
import tuiListCell from '@/components/list-cell/list-cell';
import tuiDatetime from '@/components/dateTime/dateTime';
const QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');

// var util = require('../../common/util.js');
// var formatLocation = util.formatLocation;
export default {
	components: {
		tuiListCell,
		tuiDatetime
	},
	computed: {
		// ...mapState(['userInfo'])
		...mapState({
		})
	},
	data() {
		return {
			$cdn:this.$cdn,
			actFile: '',
			actFilePath: '',
			actGroupFile: '',
			actGroupFilePath: '',

			startYear: 1980,
			endYear: 2030,
			cancelColor: '#888',
			color: '#5677fc',
			setDateTime: '2019-09-09 23:00:00',
			startTime: '请选择',
			endTime: '请选择',

			selectActTypeIndex: 0,
			actTypeList: [{ title: '请选择', actTypeId: 0 }],
			actItem: {},
			qqmapsdk: null,
			latitude:  '',
			longitude: '',
			locationAddress: '请选择',
			cityCode:'',
			// 当前页面是否已定位，如为默认取首页的定位信息
			hasLocation: false,
			// 编辑时用
			actId:''
		};
	},
	onLoad: function(data) {
		this.qqmapsdk = new QQMapWX({
			key: 'W4WBZ-TUD65-IDAIR-QPM36-HMFQ5-CGBZP'
		});
		// groupId 如有则是编辑模式
		if(data.actId){
			this.actId=data.actId;
		}
		if(data.coverFile){
			this.actFile=data.coverFile;
		}
		if(data.coverFilePath){
			this.actFilePath=data.coverFilePath;
		}
		this.getActTypeList();
	},
	created() {
		
	},
	methods: {
		// 判断是否进入详情修改页面
		isEditDesc(){
			if(this.actGroupFile==this.$cdn.actGroupQR+this.actItem.qrcode){
				return true;
			}else{
				return false;
			}
		},
		// 是否修改封面
		isEditCoverImg(){
			if(this.actFile==this.$cdn.actCoverImg+this.actItem.coverImg || this.actFile.indexOf('default')>0){
				return false;
			}else{
				return true;
			}
		},
		// 是否修改二维码
		isEditQrcode(){
			if(this.actGroupFile==this.$cdn.actGroupQR+this.actItem.qrcode){
				return false;
			}else{
				return true;
			}
		},
		toCoverSelect(){
			uni.navigateTo({
				url:'/pages/act/cover-select?actId='+this.actId
			});
		},
		geActDetail(actId) {
			let postData = { actId: actId };
			this.tui
				.request('/api/act/get.short', postData, 'POST', false, true)
				.then(res => {
					if (res.code == 0) {
						// console.log('geActDetail=' + JSON.stringify(res));
						let actDb = res.data.act;
						
						this.actItem.actId=actDb.actId;
						this.actItem.actTitle=actDb.actTitle;
						this.actItem.peopleMax=actDb.peopleMax;
						this.actItem.price=actDb.price;
						this.actItem.linkmanPhone=actDb.linkmanPhone;
						this.actItem.linkmanWx=actDb.linkmanWx;
						this.actItem.reward=actDb.reward;
						// 从db获取数据显示到页面
						if(this.actFile==''){
							this.actFile=this.$cdn.actCoverImg+actDb.coverImg;
							this.actFilePath=actDb.coverImg;
							this.actItem.coverImg=actDb.coverImg;
						}
						
						// 二维码
						this.actGroupFile=this.$cdn.actGroupQR+actDb.qrcode;
						this.actGroupFilePath=actDb.qrcode;
						this.actItem.qrcode=actDb.qrcode;
						
						this.selectActTypeIndex=actDb.actTypeId-1;
						this.locationAddress=actDb.place;
						this.startTime=actDb.startTime
						this.endTime=actDb.endTime
						this.longitude=actDb.lng;
						this.latitude=actDb.lat;
						this.locationAddress=actDb.place;
						this.cityCode=actDb.cityCode;
						// console.log('actDb='+JSON.stringify(actDb));
					}else{
						this.tui.toast(res.msg);
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		// 获取聚会分类列表
		getActTypeList() {
			//参数
			let postData = {};
			this.tui
				.request('/api/actType/getActTypeList', postData, 'GET', false, true)
				.then(res => {
					if (res.code == 0) {
						this.actTypeList=res.data;
						if(this.actId){
							this.geActDetail(this.actId);
						}
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		chooseImage: function(e) {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					console.log(JSON.stringify(res));
					that.actFile = res.tempFilePaths[0];
					/* that.tui.reSizeImg(res.tempFilePaths[0], 456 * 1.5, 236 * 1.5, function(resImg) {
						that.actFile = resImg;
					}); */
				}
			});
		},
		// 上传聚会封面
		uploadActImg() {
			// console.log('this.isEditCoverImg()='+this.isEditCoverImg()+'this.actFile='+this.actFile);
			if(this.isEditCoverImg()){
				this.tui
					.uploadFile('/auth/api/act/uploadCoverImg', this.actFile)
					.then(res => {
						console.log('uploadCoverImg上传结果' + JSON.stringify(res));
						if (res.code == 0) {
							this.actFilePath = res.data;
							// return callback(res);
							this.uploadActGroupImg();
						}
					})
				
					.catch(res => {
						console.log(res);
					});
			}else{
				this.uploadActGroupImg();
			}
		},
		chooseImageGroup: function(e) {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					that.actGroupFile = res.tempFilePaths[0];
					/* that.tui.reSizeImg(res.tempFilePaths[0], null, null, function(resImg) {
						that.actGroupFile = resImg;
					}); */
				}
			});
		},
		uploadActGroupImg() {
			// console.log('this.isEditQrcode='+this.isEditQrcode());
			if(this.isEditQrcode()){
				this.tui
					.uploadFile('/auth/api/act/uploadGroupQrcode', this.actGroupFile)
					.then(res => {
						console.log('uploadGroupQrcode上传结果' + JSON.stringify(res));
						if (res.code == 0) {
							this.actGroupFilePath = res.data;
							// return callback(res);
							this.save();
						}
					})
					.catch(res => {
						console.log(res);
					});
				}else{
					this.save();
				}
		},
		// 后端保存接口
		save: function() {
			// 不管新增还是修改过，重新赋值一遍
			console.log('前' + JSON.stringify(this.actFilePath));
			this.actItem.coverImg = this.actFilePath;
			this.actItem.qrcode = this.actGroupFilePath;
			console.log('后' + JSON.stringify(this.actFilePath));
			this.actItem.actTypeId = this.actTypeList[this.selectActTypeIndex].actTypeId;
			this.actItem.startTimeStr = this.startTime;
			this.actItem.endTimeStr = this.endTime;
			this.actItem.lng = this.longitude;
			this.actItem.lat = this.latitude;
			this.actItem.place = this.locationAddress;
			this.actItem.cityCode = this.cityCode;

			this.tui
				.request('/auth/api/act/save', this.actItem, 'POST', false, true)
				.then(res => {
					if (res.code == 0) {
						console.log('save' + JSON.stringify(res));
						// 页面跳转
						if(this.isEditDesc()){
							uni.navigateTo({
								url:'/pages/act/act-edit-desc?type=edit&actId='+res.data.actId
							})
						}else{
							uni.navigateTo({
								url:'/pages/act/act-edit-desc?actId='+res.data.actId
							})
						}
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'error'
						});
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		formSubmit: function(e) {
			// 图片校验
			if (this.actFile == undefined || this.actFile == '') {
				uni.showToast({
					title: '请上传封面图片',
					icon: 'error'
				});
				return false;
			}
			if (this.actTypeList[this.selectActTypeIndex].actTypeId == 0) {
				uni.showToast({
					title: '请选择分类',
					icon: 'error'
				});
				return false;
			}
			if (this.startTime == '请选择') {
				uni.showToast({
					title: '请选择开始时间',
					icon: 'error'
				});
				return false;
			}
			if (this.endTime == '请选择') {
				uni.showToast({
					title: '请选择结束时间',
					icon: 'error'
				});
				return false;
			}
			if (this.locationAddress == undefined || this.locationAddress == '请选择') {
				uni.showToast({
					title: '请选择地点',
					icon: 'error'
				});
				return false;
			}
			if (this.actGroupFile == undefined || this.actGroupFile == '') {
				uni.showToast({
					title: '请上传群二维码',
					icon: 'error'
				});
				return false;
			}
			if (this.linkmanPhone == '' && this.linkmanWx=='') {
				uni.showToast({
					title: '联系手机和微信至少要填一个',
					icon: 'error'
				});
				return false;
			}

			// 表单规则
			let rules = [
				{
					name: 'actTitle',
					rule: ['required', 'minLength:4', 'maxLength:100'], //可使用区间，此处主要测试功能
					msg: ['请输入主题', '主题必须4个或以上字符', '主题不能超过100个字符']
				},
				{
					name: 'peopleMax',
					rule: ['required', 'range:[2,999999]'],
					msg: ['请输入最大参与人数', '最大参与人数要大于2']
				},
				{
					name: 'price',
					rule: ['required', 'isAmount'],
					msg: ['请输入预计费用', '请输入正确的金额，允许保留两位小数']
				},
				{
					name: 'linkmanPhone',
					rule: ['isMobile'],
					msg: ['请输入正确的手机号']
				}
			];
			// 进行表单检查
			let formData = e.detail.value;
			// console.log('formData=' + JSON.stringify(formData));
			let checkRes = form.validation(formData, rules);
			if (!checkRes) {
				// this.actItem = formData;
				// this.actItem.actTitle = formData.actTitle;
				// 调用后端接口保存，先上传图片再保存数据
				this.uploadActImg();
			} else {
				uni.showToast({
					title: checkRes,
					icon: 'none'
				});
			}
		},
		formReset: function(e) {
			console.log('清空数据');
		},
		// 日期控件
		showStartTime: function() {
			this.$refs.startTime.show();
		},
		changeTimeStart: function(e) {
			console.log(e);
			this.startTime = e.result;
		},
		showEndTime: function() {
			this.$refs.endTime.show();
		},
		changeTimeEnd: function(e) {
			console.log(e);
			this.endTime = e.result;
		},
		// 选择位置
		chooseLocation: function() {
			let that=this;
			uni.chooseLocation({
				success: res => {
					console.log(JSON.stringify(res));
					that.hasLocation = true;
					that.longitude=res.longitude;
					that.latitude=res.latitude;
					// that.location = formatLocation(res.longitude, res.latitude);
					that.locationAddress = res.name;
					// 根据经纬度，获取城市city_code
					// 根据经纬度获取地址信息
					that.qqmapsdk.reverseGeocoder({
						location: {
							latitude:  res.latitude,
							longitude: res.longitude
						},
						success: resTwo => {
							console.log(JSON.stringify(resTwo));
							that.cityCode=resTwo.result.ad_info.adcode;
						},
						fail: res => {
							// this.address = '获取位置信息失败';
						}
					});
				}
			});
		},
		clear: function() {
			this.hasLocation = false;
		},
		bindPickerChange: function(e) {
			console.log('picker发送选择改变，携带值为：' + e.target.value);
			this.selectActTypeIndex = e.target.value;
		}
	}
};
</script>

<style>
/* @import '../../static/style/thorui.css'; */
.container {
	padding: 0rpx 0 10rpx 0;
}

.tui-line-cell {
	width: 100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
}

.tui-title {
	line-height: 32rpx;
	flex-shrink: 0;
}

.tui-input {
	font-size: 32rpx;
	color: #333;
	padding-left: 20rpx;
	flex: 1;
}

.radio-group {
	margin-left: auto;
	transform: scale(0.8);
	transform-origin: 100% center;
	flex-shrink: 0;
}

.tui-radio {
	display: inline-block;
	padding-left: 28rpx;
	font-size: 36rpx;
	vertical-align: middle;
}

.tui-btn-box {
	padding: 40rpx 50rpx;
	box-sizing: border-box;
}

.btn-gray {
	margin-top: 30rpx;
}

.tui-tips {
	padding: 30rpx;
	color: #999;
	font-size: 24rpx;
}

.tui-upload-box {
	flex-flow: column;
	width: 100%;
	height: 100%;
}
.tui-line-cell-img {
	display: flex;
	height: 390rpx;
	width: 100%;
}
.tui-upload-item {
	width: 100%;
	height: 390rpx;
	border: 1rpx solid #e6e6e6;
	box-sizing: border-box;
	border-radius: 4rpx;
}
.tui-line-cell-img-group {
	display: flex;
	width: 50%;
}
.tui-upload-item-group {
	height: 200rpx;
	border: 1rpx solid #e6e6e6;
	box-sizing: border-box;
	border-radius: 4rpx;
	margin-left: 20rpx;
}
.tui-upload-item-text {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}
.tui-upload-img {
	width: 100%;
	height: 100%;
}

.tui-title-value {
	margin-left: 30rpx;
	width: 100%;
}
</style>
